<template>

  <!-- 弹出对话框进行修改用户信息 -->
  <el-dialog v-model="dialogTableVisible" title="修改用户信息">
    <el-form :model="user" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="年龄">
        <el-col :span="11">
          <el-date-picker
              v-model="user.age"
              type="date"
              placeholder="Pick a date"
              style="width: 100%"
          ></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="user.gender">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="user.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input v-model="user.address"></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="user.conInfo"></el-input>
      </el-form-item>
      <el-form-item label="角色">
        <el-checkbox-group v-model="roleList">
          <el-checkbox label="超级管理员" name="type"></el-checkbox>
          <el-checkbox label="管理员" name="type"></el-checkbox>
          <el-checkbox label="普通用户" name="type"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">修改</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 批量操作按钮 -->
  <el-button type="primary" @click="addUser">新增用户</el-button>
  <el-button type="danger" @click="batchDelete">批量删除</el-button>

  <el-table
      :data="userList"
      style="width: 100%"
      @select="select"
  >
    <el-table-column type="selection" width="55"/>
    <el-table-column label="用户名" prop="username"/>
    <el-table-column label="出生日期" prop="age"/>
    <el-table-column label="性别" prop="gender"/>
    <el-table-column label="电话" prop="phone"/>
    <el-table-column label="邮箱" prop="email"/>
    <el-table-column label="角色" prop="roleList"/>
    <el-table-column label="地址" prop="address"/>
    <el-table-column label="描述" prop="conInfo"/>
    <el-table-column align="right">
      <template #header>
        <el-input :change="searchUser" v-model="search" size="mini" placeholder="Type to search"/>
      </template>
      <template #default="scope">
        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!--  页码显示  -->
  <page :pageInfo="pageInfo" @handleCurrentChange="handleCurrentChange"/>
</template>

<script lang="ts">
import {onBeforeMount, reactive, Ref, ref} from "vue";


import {DELETE, POST, PUT} from "@/api";
import {ElMessage, ElMessageBox} from "element-plus";

import Page from "@/components/page/Page.vue"

export default {
  name: "UserList",
  components: {
    Page,
  },
  setup() {
    const user = ref<any>({})
    const userList = ref()
    const isEdit = ref(false)
    const pageInfo = reactive({
      // 当前页
      currentPage: 1,
      // 每页的数量
      pageSize: 10,
      // 总条目数
      total: 10
    })
    const dialogTableVisible = ref(false)
    const roleList: Ref<any> = ref([])
    const selectList = ref([])

    const search = ref("")
    const handleEdit = (index: any, row: any) => {
      dialogTableVisible.value = true
      user.value = row
      roleList.value = user.value.roleList
    }

    const handleDelete = (index: any, row: any) => {
      ElMessageBox.confirm(
          '确定要删除' + row.username + '用户吗?',
          'Warning',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        DELETE(`/user/delete/${row.userId}`, {
          params: {
            isLogout: false
          }
        }).then(res => {
          if (res.status === 200) {
            ElMessage.success("删除用户" + row.username + "成功")
            loadUser()
          }
        }).catch(err => {
          console.log(err)
          ElMessage.error("出错啦")
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消操作',
        })
      })
    }

    const searchUser = () => {
      // TODO 搜索用户
      console.log("更改用户")
    }

    const loadUser = () => {
      PUT(`/user/findAll/${pageInfo.currentPage}/${pageInfo.pageSize}`, {}, {}).then(res => {
        if (res.status === 200) {
          userList.value = res.data.records
          for (let index in userList.value) {
            // 对用户角色进行格式化处理
            userList.value[index].roleMap && (userList.value[index].roleMap =
                Object.values(userList.value[index].roleMap).toString().replaceAll(",", "、"))
            // 对日期进行格式化处理
            userList.value[index].age = new Date(userList.value[index].age).toLocaleDateString()
            // 对性别进行处理
            userList.value[index].gender = userList.value[index].gender == 1 ? '男' : '女'
            // 对角色进行处理
            if (userList.value[index].roleList != null) {
              const roleList = userList.value[index].roleList
              let roleNames: String = "";
              roleList.forEach((item: any) => {
                roleNames += item.roleName + "、"
              })
              if (roleNames.slice(-2, -1) != "、") {
                userList.value[index].roleList = roleNames.slice(0, -1)
              }
            }
          }
          pageInfo.currentPage = res.data.current
          pageInfo.total = res.data.total
        }
      }).catch(err => {
        console.log(err)
      })
    }

    const handleCurrentChange = (index: number) => {
      pageInfo.currentPage = index
      loadUser()
    }

    onBeforeMount(() => {
      loadUser()
    })

    const onSubmit = () => {
      const roles: { roleId: number; roleName: any; }[] = []
      // 对用户的性别进行格式化
      user.value.gender = (user.gender == '男' ? 1 : 0)
      user.value.age = new Date(user.value.age).toLocaleDateString()
      // 对用户的角色列表进行格式化
      roleList.value.forEach((item: any) => {
        // TODO 此处不能写死
        if (item === "超级管理员") {
          roles.push({
            roleId: 1,
            roleName: item
          })
        }
        if (item === "管理员") {
          roles.push({
            roleId: 2,
            roleName: item
          })
        }
        if (item === "普通用户") {
          roles.push({
            roleId: 3,
            roleName: item
          })
        }
      })
      user.value.roleList = roles

      // TODO 用户封装传来数据失败
      PUT("/user/update", {
        ...user.value
      }, {}).then(res => {
        ElMessage.success("操作成功")
        dialogTableVisible.value = false
      }).catch(err => {
        ElMessage.error("操作失败")
      })
    }

    const onCancel = () => {
      dialogTableVisible.value = false
    }

    const batchDelete = () => {
      ElMessageBox.confirm(
          '确定要删除吗?',
          'Warning',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        const idList: any[] = []
        selectList.value.forEach((item: any) => {
          idList.push(item.userId)
        })

        POST("/user/batchDelete", [...idList]).then(res => {
          ElMessage.success("删除用户成功")
          loadUser()
        }).catch(err => {
          ElMessage.error("网络异常")
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消操作',
        })
      })
    }
    const select = (selections: any, row: any) => {
      selectList.value = selections
    }

    const addUser = () => {
      dialogTableVisible.value = true
    }

    return {
      roleList,
      userList,
      user,
      search,
      isEdit,
      handleDelete,
      handleEdit,
      pageInfo,
      handleCurrentChange,
      searchUser,
      dialogTableVisible,
      onSubmit,
      onCancel,
      batchDelete,
      addUser,
      select
    }
  }
}
</script>
